<template>
  <div class="login-body">
    <div class="bg"></div>
    <div class="login-panel">
      <el-form :model="formData" :rules="rules" ref="loginFormRef" class="login-register">
        <div class="login-title">我的云盘</div>
        <el-form-item prop="mobile" v-if="opType == 0 || opType == 2 || opType == 1" >
          <el-input
            clearable
            placeholder="请输入手机号"
            v-model.trim="formData.mobile"
            :prefix-icon="PhoneOutlined"
            maxLength="150"
          />
        </el-form-item>
        <el-form-item prop="password" v-if="opType == 1">
          <el-input
            show-password
            type="password"
            placeholder="请输入密码"
            v-model.trim="formData.password"
            :prefix-icon="LockOutlined"
            maxLength="20"
          />
        </el-form-item>
        <!-- 注册 -->
        <el-form-item prop="username" v-if="opType == 0">
            <el-input
              placeholder="请输入昵称"
              v-model.trim="formData.username"
              :prefix-icon="UserOutlined"
              maxLength="20"
            />
          </el-form-item>
           <el-form-item prop="password" v-if="opType == 0">
            <el-input
              show-password
              type="password"
              placeholder="请输入密码"
              v-model.trim="formData.password"
              :prefix-icon="LockOutlined"
              maxLength="20"
            />
          </el-form-item>
          <el-form-item prop="reRegisterPassword" v-if="opType == 0">
            <el-input
              show-password
              type="password"
              placeholder="请再次输入密码"
              v-model.trim="formData.reRegisterPassword"
              :prefix-icon="LockOutlined"
              maxLength="20"
            />
          </el-form-item>
        <div v-if="opType == 0 || opType == 2">
          <el-form-item prop="smsCode">
            <div class="send-phone-panel">
              <el-input
                placeholder="请输入手机验证码"
                v-model.trim="formData.smsCode"
                :prefix-icon="SafetyCertificateOutlined"
                
              />
              <el-button class="send-phone-btn" type="primary" @click="getSmsCode" :disabled="isDisabled">
    {{ buttonText }}
  </el-button>
            </div>
            <el-popover placement="left" :width="500" trigger="click">
              <div>
                <p>未收到短信验证码？请检查是否设置了短信拦截。</p>
              </div>
              <template #reference>
                <el-link type="primary" :underline="false">未收到短信验证码？</el-link>
              </template>
            </el-popover>
          </el-form-item>
        </div>
        <el-form-item prop="captchaCode" v-if="opType == 1">
  <div class="check-code-panel">
    <el-input
      placeholder="请输入图形验证码"
      v-model.trim="formData.captchaCode"
      :prefix-icon="SafetyCertificateOutlined"
      @keyup.enter="doSubmit"
    />
    <img :src="captchaSrc" class="check-code" @click="changeCheckCode" />
  </div>
</el-form-item>
        <!-- 登陆 -->
        <el-form-item v-if="opType == 1">
          <div class="no-account">
            <el-link type="primary" :underline="false" @click="showPanel(2)">验证码登录？</el-link>
            <el-link type="primary" :underline="false" @click="showPanel(0)">没有账号？</el-link>
          </div>
        </el-form-item>
        <!-- 手机验证码密码 -->
        <el-form-item v-if="opType == 2">
          <div class="no-account">
            <el-link type="primary" :underline="false" @click="showPanel(1)">去登陆</el-link>
          </div>
        </el-form-item>
        <!-- 注册 -->
        <el-form-item v-if="opType == 0">
          <div class="no-account">
            <el-link type="primary" :underline="false" @click="showPanel(1)">已有账号？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="doSubmit">
            <span v-if="opType == 0">注册</span>
            <span v-if="opType == 1">登陆</span>
            <span v-if="opType == 2">登陆</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, onMounted,inject, } from "vue";
import { useRouter} from "vue-router";
import http from "@/utils/http";
let $message = inject('$message');
const { proxy } = getCurrentInstance();
const router = useRouter();
const isDisabled = ref(false);
const buttonText = ref('发送验证码');



// 0:注册 1:登录 2:重置密码
const opType = ref();
const showPanel = (type) => {
  opType.value = type;
  resetForm();
};

onMounted(() => {
  showPanel(1);
  changeCheckCode(); 
});

//验证码
const captchaSrc = ref(''); 
const captchaId = ref('');
const changeCheckCode = async () => {
  http.get('/user/captcha', { responseType: 'blob' })
    .then(response => {
      const urlCreator = window.URL || window.webkitURL;
      const imageUrl = urlCreator.createObjectURL(new Blob([response.data]));
      captchaSrc.value = imageUrl;
      captchaId.value = response.headers['captcha-id'];
      console.log('Response headers:', response.headers); 
    })
    .catch(error => {
      console.error('Error fetching captcha:', error);
    });
};
// 获取手机验证码
let timer;

const getSmsCode = async () => {
  if (isDisabled.value) return;

  
    isDisabled.value = true;
    let count = 60;
    buttonText.value = `重新发送 (${count}s)`;

    timer = setInterval(() => {
      count--;
      buttonText.value = `重新发送 (${count}s)`;
      if (count <= 0) {
        clearInterval(timer);
        isDisabled.value = false;
        buttonText.value = '发送验证码';
      }
    }, 1000);

    // 发送请求
    const data = await http.post('/user/sendCode', formData.value);
    console.log('SMS Code Sent:', data);
    if (data.code >= 400) {
      clearInterval(timer);
      isDisabled.value = false;
      buttonText.value = '发送验证码';
      return $message({
        showClose: true,
        message: data.msg,
        type: 'warning'
      });
    }
};


//登录，注册 弹出配置
const dialogConfig = reactive({
  show: false,
  title: "标题",
});

const checkRePassword = (rule, value, callback) => {
  if (value !== formData.value.password) {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};
const formData = ref({
  createTime: '',
});
const loginFormRef = ref();
const rules = reactive({
  mobile: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: proxy.Verify.mobile, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  // password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  username: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: proxy.Verify.password, message: '密码只能是数字, 字母, 特殊字符8-18位', trigger: 'blur' }
  ],
  reRegisterPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: checkRePassword, message: '两次密码不一致', trigger: 'blur' }
  ],
  captchaCode: [{ required: true, message: '请输入图片验证码' }],
  smsCode: [{ required: true, message: '请输入短信验证码' }]
});

//重置表单
const resetForm = () => {
  dialogConfig.show = true;
  if (opType.value == 0) {
    dialogConfig.title = "注册";
  } else if (opType.value == 1) {
    dialogConfig.title = "登陆";
    // router.push("/");
  } else if (opType.value == 2) {
    dialogConfig.title = "重置密码";
  }
  nextTick(() => {
    // changeCheckCode();
    loginFormRef.value.resetFields();
    formData.value = {};
  });
};
// 提交表单
const doSubmit = async () => { // 确保 doSubmit 是一个异步函数
  try {
    const valid = await loginFormRef.value.validate(); // 使用 validate 方法检查表单是否有效
    if (!valid) return;

    // let params = {};
    // Object.assign(params, formData.value);

    switch (opType.value) {
      case 0: { // 注册
        formData.value.createTime = new Date(Date.now() + 28800000).toISOString().slice(0, 19).replace('T', ' ');
        const data = await http.post('/user/register', formData.value, {
    params: {
        code: formData.value.smsCode, 
    }
});

        if (data.code >= 400) {
          return $message({
            showClose: true,
            message: data.msg,
            type: 'warning'
          });
        }
       $message({
        showClose: true,
        message: '注册成功, 等待跳转即可',
        type: 'success'
      });
        showPanel(1);
        break;
      }
      case 1: {//手机密码登录
        const data = await http.post('/user/login', formData.value,{
          params: {
          captchaCode: formData.value.captchaCode,
          captchaId: captchaId.value,
          }
        });
        console.log('登录', data.code)
        if (data.code >= 400) {
          return $message({
        showClose: true,
        message: data.msg,
        type: 'warning'
      });
    }
    $message({
      showClose: true,
      message: '登陆成功, 等待跳转即可',
      type: 'success'
    });
    localStorage.setItem('access-token', data.data['access-token']);
    toShare();
   const userId=data.data['user'].userId;
        break;
      }
      case 2: { //手机验证码登录
        const data = await http.post('/user/logon', formData.value,{
          params: {
            code: formData.value.smsCode,
          }
        })
        if (data.code >= 400) {
      return $message({
        showClose: true,
        message: data.msg,
        type: 'warning'
      });
    }
    $message({
      showClose: true,
      message: '登陆成功, 等待跳转即可',
      type: 'success'
    });
    localStorage.setItem('access-token', data.data['access-token']);
    toShare();
        break;
      }
    }
  } catch (error) {
    console.error(error);
  }
};

const closeDialog = () => {
  dialogConfig.show = false;
};

const toShare = () => {
  console.log(localStorage.getItem('link'));
  
  if (localStorage.getItem('link')) {
      const url = localStorage.getItem('link');
      localStorage.removeItem('link');
      
      router.push(url);
    }else{
      router.push("/main")
    }
}
</script>

<style lang="scss" scoped>
.login-body {
  height: calc(100vh);
  background-size: cover;
  background: url("../assets/login_bg.jpg");
  display: flex;
  .bg {
    flex: 1;
    background-size: cover;
    background-position: center;
    background-size: 800px;
    background-repeat: no-repeat;
    background-image: url("../assets/login_img.png");
  }
  .login-panel {
    width: 430px;
    margin-right: 15%;
    margin-top: calc((100vh - 500px) / 2);
    .login-register {
      padding: 25px;
      background: #fff;
      border-radius: 5px;
      .login-title {
        text-align: center;
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
      }
      .send-emali-panel {
        display: flex;
        width: 100%;
        justify-content: space-between;
        .send-mail-btn {
          margin-left: 5px;
        }
      }
      .rememberme-panel {
        width: 100%;
      }
      .no-account {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }
      .op-btn {
        width: 100%;
      }
    }
  }
  .send-phone-panel{
    width: 100%;
    display: flex;
    .send-phone-btn{
      width: 45%;
      margin-left: 5px;
      cursor: pointer;
    }
  }
  }
  .check-code-panel {
    width: 100%;
    display: flex;
    .check-code {
      margin-left: 5px;
      cursor: pointer;
    }
  }
  .login-btn-qq {
    margin-top: 20px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    img {
      cursor: pointer;
      margin-left: 10px;
      width: 20px;
    }
  }

</style>